package com.example.imitation_webchat_demo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.Menu;
import android.view.Window;
import android.widget.TextView;

import com.example.imitation_webchat_demo.R;
import com.example.imitation_webchat_demo.model.MyHandler;
import com.example.imitation_webchat_demo.model.Resource;
import com.example.imitation_webchat_demo.util.AppUtils;
import com.example.imitation_webchat_demo.util.ApplicationUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

// 仿微信的引导界面
public class GuideActivity extends Activity {
	@ViewInject(R.id.guide_version)
	private TextView versionView;
	
	private static int what_0 = 0;
	private static int what_1 =1;
	
	private MyHandler handler = new MyHandler(this){
		@Override
		public void handleMessage(Message msg) {
			Intent intent = null;
			if(msg.what == what_0){
				intent = new Intent(GuideActivity.this, LoginActivity.class);
			}else if(msg.what == what_1){
				intent = new Intent(GuideActivity.this, MainActivity.class);
			}
			GuideActivity.this.startActivity(intent);
			GuideActivity.this.finish();
		}
	};
	
	private Runnable runnable = new Runnable(){
		@Override
		public void run() {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if(judgeUsernameExist()){   // 如果用户存在，则进入主页面
				handler.sendEmptyMessage(what_1);
			}else{                              // 如果用户不存在，则进入登录页面
				handler.sendEmptyMessage(what_0);
			}
		}
	};
	
	//判断用户是否存在
	private boolean judgeUsernameExist(){
		boolean flag = false;
		String username = getSharedPreferences(Resource.appName, Context.MODE_PRIVATE).getString("username", null);
		if(username != null && !username.equals("")){
			flag = true;
		}
		return flag;
       
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_guide);
		
		ViewUtils.inject(this);  // 注册ViewUtils
		initComponent();   // 初始化控件
		
		ApplicationUtils.getInstance().addActivity(this);
	}

	// 初始化控件
	private void initComponent(){
		versionView.setText("版本名称：" + AppUtils.getVersionName(this));
		new Thread(runnable).start();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		ApplicationUtils.getInstance().removeActivity(this);
		super.onDestroy();
	}
}